package com.kyzh.core.pager.gamedetail

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.graphics.Rect
import android.os.Bundle
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.atools.util.setHeight
import com.gushenge.core.beans.GameBottomDetail
import com.gushenge.core.beans.Pinglun
import com.gushenge.core.impls.GameImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.R
import com.kyzh.core.activities.CommentDetailActivity
import com.kyzh.core.adapters.GameDetailBannerAdapter
import com.kyzh.core.adapters.GameDetailBannerAdapter1
import com.kyzh.core.adapters.GameDetailLikeAdapter
import com.kyzh.core.databinding.HeaderVideoBinding
import com.kyzh.core.databinding.ItemDynamicDiscussBinding
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.isShangjia
import com.kyzh.core.utils.*
import com.littlejerk.rvdivider.builder.XGridBuilder
import com.shuyu.gsyvideoplayer.GSYVideoManager
import kotlinx.android.synthetic.main.fragment_game_detail.*
import org.jetbrains.anko.support.v4.dip
import org.jetbrains.anko.support.v4.toast


class GameDetailFragment: BaseFragment(), ResultListener {
    private lateinit var context:Activity
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_game_detail,container,false)
        context = requireActivity()

        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
        initTab()
    }

    override fun onResume() {
        super.onResume()
        initPingLun1()
    }

    private fun initTab(){
        GameImpl.gameDetailTab1(this)

    }
    private fun initPingLun1 (){

        if(isShangjia){
            tvTitlePingLun.setVisibility(false)
            pinglun.setVisibility(false)
            tvPingLunAll.setVisibility(false)
        }
        tvPingLunAll.setVisibility(false)

        GameImpl.getPingLun{
            if(this!=null &&this.size >2){
                if(isShangjia){
                    tvTitlePingLun.setVisibility(false)
                    pinglun.setVisibility(false)
                    tvPingLunAll.setVisibility(false)
                }else{
                    tvPingLunAll.setVisibility(true)
                }
            }
            initPinglun(this)
        }
    }


    private fun initView() {
        tvPingLunAll.setOnClickListener {
            (context as GameDetailActivity1).checkTab(1)
        }
    }
    override fun success(game: Any) {
        game as GameBottomDetail
        initBanner(game.imgs)
        initSummary(game.content)
        initLike(game.cnlike)
        if (game.fuli.isNullOrEmpty()) {
            tvFuli.visibility = View.GONE
            weal.visibility = View.VISIBLE
        } else {
            tvFuli.visibility = View.VISIBLE
            val replace = game.fuli.replace("\r", "<br>")
            tvFuli.text = Html.fromHtml(replace)
            weal.visibility = View.GONE
        }



    }

    private fun initLike(game:  ArrayList<GameBottomDetail.Cnlike>) {
        if(game.isNullOrEmpty()){
            return
        }
        like.layoutManager = object :LinearLayoutManager(context,RecyclerView.HORIZONTAL,false){
            override fun canScrollVertically(): Boolean {
                return false
            }

            override fun canScrollHorizontally(): Boolean {
                return true
            }
        }
        val adapter = GameDetailLikeAdapter(R.layout.game_detail_like_item,game)
        like.adapter = adapter
        adapter.setOnItemClickListener { adapter, view, position ->
            startGameDetailActivity(game[position].id.toString())
        }
    }

    private fun initPinglun( lb: ArrayList<Pinglun>?) {
        pinglun.layoutManager = object :LinearLayoutManager(context){
            override fun canScrollHorizontally(): Boolean {
                return false
            }

            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        if(lb!=null&&lb.size>2){
            val take = lb.take(2)
            lb.clear()
            lb.addAll(take)
        }
        val adapter = PinglunAdapter(lb)
        adapter.setOnItemClickListener { adapter, view, position ->
            CommentDetailActivity.start(context, lb?.get(position))
        }
        pinglun.adapter = adapter
        val inflate = LayoutInflater.from(context).inflate(R.layout.empty, null)
        val tv1 = inflate.findViewById<TextView>(R.id.tv1)
        tv1.text = "暂无评论"
        adapter.setEmptyView(inflate)

        adapter.setOnItemClickListener { adapter, view, position ->
        }
    }

    private fun initSummary(content: String) {
        summary.setText(content)
        summary.resetState(true)
    }
    private fun getLocalVisibleRect(context: Context, view: View, offsetY: Int): Boolean {
        val p = Point()
        (context as Activity).windowManager.defaultDisplay.getSize(p)
        val screenWidth: Int = p.x
        val screenHeight: Int = p.y
        val rect = Rect(0, 0, screenWidth, screenHeight)
        val location = IntArray(2)
        location[1] = location[1] + ViewUtils.getPx(context, offsetY)
        view.getLocationInWindow(location)
        view.tag = location[1] //存储y方向的位置
        return view.getLocalVisibleRect(rect)
    }
    @SuppressLint("NewApi")
    private fun initBanner(images: GameBottomDetail.Imgs) {
        //banner  超出位置暂停
        if(images==null || images.imgs.isNullOrEmpty()){
            GSYVideoManager.onPause()
            return
        }
        gameNsv?.setOnScrollChangeListener {view, i, i2, i3, i4 ->
            val localVisibleRect = getLocalVisibleRect(requireContext(), banner, 1120)
            if(!localVisibleRect){
                if(GSYVideoManager.instance().isPlaying){
                    GSYVideoManager.onPause()
                }
            }
        }


        val bannerLayoutManager = object :LinearLayoutManager(context,RecyclerView.HORIZONTAL,false){
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        var imgs = images.imgs.clone()
        imgs as ArrayList<String>
        banner.layoutManager = bannerLayoutManager
//        if(!images.video.video_url.isNullOrEmpty()){
//            imgs.add(0,"")
//        }
        val bannerAdapter = GameDetailBannerAdapter1(imgs)
        banner.adapter = bannerAdapter

        if(images.video.video_url.isNotEmpty()){
            bannerAdapter.removeAllHeaderView()
            val inflate = HeaderVideoBinding.inflate(layoutInflater)
            inflate.scv.setConfig(images.video.video_url,images.video.video_pic)
            bannerAdapter.addHeaderView(inflate.root)
        }

        bannerAdapter.setOnItemClickListener { adapter, view, position ->
            reviewImages(images.imgs, position)
        }
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
        Log.e("TAG", "onPause: ", )
    }
    override fun error(error: String) {
        toast(error)
    }
    inner class PinglunAdapter(var lb: ArrayList<Pinglun>?):BaseQuickAdapter<Pinglun, BaseDataBindingHolder<ItemDynamicDiscussBinding>>(R.layout
        .item_dynamic_discuss,lb) {
        @SuppressLint("UseCompatLoadingForDrawables")
        override fun convert(holder: BaseDataBindingHolder<ItemDynamicDiscussBinding>, item: Pinglun) {
            holder.dataBinding?.apply {

                if(item.color.isNullOrEmpty()){
                    tvName.setTextSize(14f)
                    tvName .setHasColors(false,null)

                    tvName.setText(item.user_name)
                }else{
                    if(item.color.size == 1){
                        tvName.setTextSize(14f)
                        tvName.setText(item.user_name)
                        tvName .setHasColors(false,null)
                        tvName.setTextColor(Color.parseColor(item.color[0]))
                    }else{
                        var intArray = IntArray(item.color!!.size)
                        item.color?.forEachIndexed { index, s ->
                            intArray[index] = Color.parseColor(s)
                        }

                        tvName.setTextSize(14f)
                        tvName.setTextColor(Color.parseColor(item.color[0]))
                        tvName.setText(item.user_name)
                        tvName .setHasColors(true,intArray)
                    }
                }
                if(!item.video.isNullOrEmpty()){
                    rvList.setHeight(dip(160))
                    val bannerLayoutManager = object : GridLayoutManager(context, 1){
                        override fun canScrollHorizontally(): Boolean {
                            return false
                        }
                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rvList.setVisibility(true)
                    rvList.layoutManager = bannerLayoutManager
                    var list = arrayListOf<String>()
                    if(item.images==null||item.images.size==0){
                        list.add(String())
                    }else{
                        list =  item.images
                    }
                    val gameDetailBannerAdapter = GameDetailBannerAdapter(R.layout.game_detail_banner_item1, list, item.video)
                    rvList.adapter = gameDetailBannerAdapter

                    gameDetailBannerAdapter.setOnItemClickListener { adapter, view, position ->
                        reviewImages(item.images, position)
                    }
                }else if(item.images!=null&& item.images.size>0&& item.images[0] != "http:"&&item.images[0]!=""){
                    val bannerLayoutManager = object : GridLayoutManager(context, 6){
                    }
                    val value = object : GridLayoutManager.SpanSizeLookup() {
                        override fun getSpanSize(position: Int): Int {
                            return when (item.images.size) {
                                1 ->6
                                2 ->3
                                else -> 2
                            }
                        }
                    }
                    bannerLayoutManager.spanSizeLookup =value
                    rvList.setVisibility(true)
                    rvList.layoutManager = bannerLayoutManager
                    val gameDetailBannerAdapter = GameDetailBannerAdapter(R.layout.game_detail_banner_item1, item.images, item.video,false)
                    rvList.adapter = gameDetailBannerAdapter
                    if(item.images!=null &&item.images?.size==1){
                        rvList.setHeight(dip(125))
                    }else
                        if(item.images!=null &&item.images?.size==2){
                            rvList.setHeight(dip(95))
                        }else{
                            if(item.images?.size!!%3==0){
                                rvList.setHeight(dip(95)*(item.images?.size!!/3))
                            }else{
                                rvList.setHeight(dip(95)*(item.images?.size!!/3)+1)
                            }
                        }
                    gameDetailBannerAdapter.setOnItemClickListener { adapter, view, position ->
                        reviewImages(item.images, position)
                    }
                } else{
                    rvList.setVisibility(false)
                }
                data = item
                if(!item.point.isNullOrEmpty()) {
                    rbStar.rating = item.point.toFloat()
                }
                val bannerLayoutManager1 = object :LinearLayoutManager(context,RecyclerView.VERTICAL,false){
                    override fun canScrollVertically(): Boolean {
                        return false
                    }
                }
                rvPingLun.layoutManager = bannerLayoutManager1
                if(item.son_list!=null&&item.son_list.size>3){
                    tvPingLunAll.setVisibility(true)
                    val take = item.son_list.take(3)
                    item.son_list.clear()
                    item.son_list.addAll(take)
                }else{
                    tvPingLunAll.setVisibility(false)
                }
                val ver =
                    XGridBuilder(requireContext()).setSpacing(3f)//这几个Spacing的优先级可看XGridBuilder说明
                        //这几个color和drawable的优先级可看XGridBuilder说明
                        .setColor(Color.BLUE)
                        //可设置颜色和drawable,drawable>color
                        .setHLineColor(Color.WHITE)
                        .setVLineColor(Color.WHITE)
                        //是否包括边界
                        .setIncludeEdge(false)
                        //竖直和水平分割线交叉处绘制的是竖直分割线颜色（交叉处属于竖直分割线）
                        .setVerticalIncludeEdge(true)
                rvList.addItemDecoration(ver.build())
                val view = holder.getView<TextViewExpandableAnimation>(R.id.tvContent)
                view.setText(item.content)
                view.resetState(true)
                val gameDetailPinglunAdapter =  GameDetailPinglunAdapter(item.son_list, item.user_name, item.id, item)
                rvPingLun.adapter = gameDetailPinglunAdapter
                gameDetailPinglunAdapter.setOnItemClickListener { adapter, view, position ->
                    CommentDetailActivity.start(context,item)
                }
                rvPingLun.setOnClickListener {
                    CommentDetailActivity.start(context,item)
                }
                tvPinglun.setOnClickListener {
                    CommentDetailActivity.start(context,item)
                }
                cilckView.setOnClickListener {
                    CommentDetailActivity.start(context,item)
                }
                if(item.son_list==null){
                    rvPingLun.setVisibility(false)
                }else{
                    rvPingLun.setVisibility(true)
                }
                tvPingLunAll.setOnClickListener {
                    CommentDetailActivity.start(context,item)
                }
                val drawable = resources.getDrawable(R.drawable.ic_zan)
                if(item.is_zan=="1"){
                    //点赞了
                    drawable.setTint(resources.getColor(R.color.colorPrimaryDark))
                    tvDianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
                }else{
                    //为点赞
                    drawable.setTint(Color.BLACK)
                    tvDianzan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
                }
                tvDianzan.setOnClickListener {
                    GameImpl.pingLunZan(item.id){

                        if(item.is_zan=="1"){
                            val i = item.zan.toInt() - 1
                            item.zan = i.toString()
                            item.is_zan ="0"
                        }else{
                            val i = item.zan.toInt() + 1
                            item.zan = i.toString()
                            item.is_zan ="1"

                        }
                        notifyItemChanged(holder.position)
                    }

                }
            }
        }
    }
}
class GameDetailPinglunAdapter(bean:ArrayList<Pinglun.PingLunSon>?, var name:String?, var ppid: String?, var pinglun1: Pinglun?):BaseQuickAdapter<Pinglun
.PingLunSon,
        BaseViewHolder>(R.layout
    .item_pinglun,
    bean) {
    override fun convert(helper: BaseViewHolder, item: Pinglun.PingLunSon) {
         var pinglun :String =if(TextUtils.equals(item.user_name,item.beihuifu_user_name)){
             "${item.user_name}:${item.content}"
         }else if (TextUtils.isEmpty(item.beihuifu_user_name)||TextUtils.equals("null",item.beihuifu_user_name)){
             "${item.user_name}:${item.content}"
         }else{
             "${item.user_name}回复${item.beihuifu_user_name}:${item.content}"
         }
        val spannableString1 = SpannableStringBuilder(pinglun)
        val span1: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
//                GameCommentActivity.start(context as Activity, SpConsts.gid,item.id ,ppid,1,pinglun1)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = context.resources.getColor(R.color.font_33)
                ds.isFakeBoldText = true
                ds.isUnderlineText = false
            }
        }
        val span2: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
//                GameCommentActivity.start(context as Activity, SpConsts.gid,item.id ,ppid,1,pinglun1)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = context.resources.getColor(R.color.font_33)
                ds.isFakeBoldText = true
                ds.isUnderlineText = false
            }
        }

        spannableString1.setSpan(span1, 0, item.user_name.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        if(!item.beihuifu_user_name.isNullOrEmpty()&&item.beihuifu_user_name!=name){
            spannableString1.setSpan(span2, item.user_name.length+2, item.user_name.length+2+item.beihuifu_user_name.length, Spannable
                .SPAN_INCLUSIVE_INCLUSIVE)
        }
        val view = helper.getView<TextView>(R.id.tvPingLun)
        view.text=spannableString1
        view.movementMethod = LinkMovementMethod.getInstance()
    }

}

